<?php
/*
 * @Date: 2022-09-25 21:23:17
 * @LastEditors: 搬铁的码农 dong2406@126.com
 * @LastEditTime: 2024-08-04 16:32:41
 */

namespace Ldy\Controller;

use Ldy\Controller\BaseAdmin;
use Ldy\Models\SysAdmin;
use Ldy\Models\SysAdminRole;
use Ldy\Models\SysMenu;
use Ldy\Models\SysRole;
// use Ldy\Models\SysRoleMenu;
use think\Request;
use think\Exception;
use think\response\Json;

class Account extends BaseAdmin{
    
     /**
     * 无需登录的方法及鉴权
     * @var array
     */
    protected $noNeedLogin = ['login'];

    /**
     * 需要登录无需鉴权的方法
     * @var array
     */
    protected $noNeedAuth = ['myMenu','logout','accountInfo','updatePassword','upload'];


    /**
     * 登录
     * {"POST":"用户登录"}
     * @param Request $request
     * @return void
     */
    public function login(Request $request){
        
        $username = $request->post('username', '');
        $password = $request->post('password', '');
        if (!$username) {
            return $this->errorJson('用户名不能为空');
        }
        $this->checkLoginLimit($username);
        $admin = SysAdmin::where('name', $username)->find();
        if (!$admin || !password_ver($password, $admin->password)) {
            return $this->errorJson('账户不存在或密码错误');
        }
        
        if(empty($admin->status)) return $this->errorJson('账户已停用！');

        $this->removeLoginLimit($username);


        $admin = $admin->toArray();
        $admin['last_login_time'] = time();
        // $session = $request->session();
        $token = generate_token($request, $admin);//$request->sessionId();
        $ip = $request->host();
// print_r($ip);
        SysAdmin::update(['last_login_ip'=>$ip,"last_login_time"=>$admin['last_login_time'], 'token'=>$token],['id'=>$admin['id']]);
        
        
        unset($admin['password']);
        $roleTalb = SysAdminRole::where('admin_id', $admin['id'])->select();

        //获取用户角色
        $role = [];
        if(!$roleTalb->isEmpty()) foreach($roleTalb as $item) $role[] = $item->role_id;
        $admin['roles'] = $role;

        $admin['nickname'] = $admin['nickname'] ? $admin['nickname']:$admin['name'];

        $data_auth = SysRole::getRoleDataAuth($role,false, $admin['department_id']);
        $admin['data_auth'] = !is_array($data_auth) && $data_auth == 'admin_id' ? $admin['id']:$data_auth;

        session('admin', $admin);
        
        return $this->successJson([
            // 'nickname' => $admin['nickname'],
            'userInfo'=> ["userId"=>$admin['id'],"userName"=>$admin['nickname'], "dashboard"=>0, "role"=>$role,'avatar'=>$admin['avatar']],
            'token' => $token,
            'isRoot' => is_root()
        ],'登录成功！');
    }

    /**
     * {"GET":"退出登录"}
     * @param Request $request
     * @return void
     */
    public function logout(Request $request){
        session('admin',null);
        //刷新session id
        session_id_refresh($request);
        return $this->successJson('退出成功');
    }

    public function myMenu(){
        $roles = admin_info('roles');
        $menus = [];
        $menuModel = (new SysMenu())->buildBtnPermission();
        if(is_root()){
            $menus = $menuModel->trees();
        }else{
            $menus = $menuModel->getUserMenu($roles);
        }
       
        $btnPermission = $menuModel->getButtonPerimssion();
        
        return $this->successJson(["menu"=>$menus,"permissions"=>$btnPermission]);
    }


    /**
     * {"GET":"查看账户信息", "POST":"修改账户信息"}
     * @param Request $request
     * @return void
     */
    public function accountInfo(Request $request){
        $aid = admin_id();

        if($request->method() == 'POST'){
            $data = $request->post();
            SysAdmin::update($data, ['id'=>$aid],['email','nickname']);
            return $this->successJson('修改成功！');
        }

        $model = SysAdmin::find($aid);

        $roles = $model->adminRoles;
        
        $rolesName = [];
        if(is_root()){
            $rolesName[] = '超级管理员';
        }else{
            foreach($roles as $role) $rolesName[] = $role->name;
        }
        
        return $this->successJson([
            "roles"=>$rolesName,
            "name" => $model->name,
            'nickname'=>$model->nickname,
            'email'=>$model->email,
            'avatar' => $model->avatar,
            'status' => $model->status,
            'last_login_ip' => $model->last_login_ip,
            'last_login_time' => $model->last_login_time
        ]);
    }

    public function updatePassword(Request $request){
        $aid = admin_id();

        $data = $request->post();

        if(empty($data['old_password'])) return $this->errorJson('请输入当前账号密码！');

        $admin = SysAdmin::find($aid);

        if($admin->isEmpty()) return $this->errorJson('非法操作！');
        
        if(!password_ver(md5($data['old_password']), $admin->password)) return $this->errorJson('当前账号密码错误！');

        if($data['password'] != $data['password2']) return $this->errorJson('两次密码不一致！');

        SysAdmin::update(['password'=>$data['password']],['id'=>$aid],['password']);

        return $this->successJson('修改密码成功！');

    }

    public function avatarUpload(){
        $avatar = $this->upload(true,[
            "validate"=>['file'=>'fileSize:502400|fileExt:jpg,png'],
            "message" => ['file'=>["fileSize"=>"上传头像不能大于500KB","fileExt"=>'头像必须为 jpg,png 格式']]
        ]);
        
        if(!is_array($avatar)) return $this->errorJson($avatar);

        $aid = admin_id();
        if(!$aid) return $this->errorJson($avatar,'更新数据失败！');

        SysAdmin::update(['avatar'=>$avatar['url']], ['id'=>$aid]);

        return $this->successJson($avatar,'上传头像成功');
    }

    public function resettingPass(Request $request): Json{
        $id = $request->param('id');
        if(!is_root() && !$id) return $this->errorJson('权限不足！');

        $rand = rand_string(8);

        SysAdmin::update(['password'=>$rand], ['id'=>$id]);

        return $this->successJson(['password'=>$rand]);
    }

    

     /**
     * 检查登录频率限制
     *
     * @param $username
     * @return void
     * @throws BusinessException
     */
    protected function checkLoginLimit($username)
    {
        $limit_log_path = runtime_path() . '/login';
        if (!is_dir($limit_log_path)) {
            mkdir($limit_log_path, 0777, true);
        }
        $limit_file = $limit_log_path . '/' . md5($username) . '.limit';
        $time = date('YmdH') . ceil(date('i')/5);
        $limit_info = [];
        if (is_file($limit_file)) {
            $json_str = file_get_contents($limit_file);
            $limit_info = json_decode($json_str, true);
        }

        if (!$limit_info || $limit_info['time'] != $time) {
            $limit_info = [
                'username' => $username,
                'count' => 0,
                'time' => $time
            ];
        }
        $limit_info['count']++;
        file_put_contents($limit_file, json_encode($limit_info));
        if ($limit_info['count'] >= 5) {
            throw new Exception('登录失败次数过多，请5分钟后再试');
        }
    }


     /**
     * 解除登录限制
     *
     * @param $username
     * @return void
     */
    protected function removeLoginLimit($username)
    {
        $limit_log_path = runtime_path() . '/login';
        $limit_file = $limit_log_path . '/' . md5($username) . '.limit';
        if (is_file($limit_file)) {
            unlink($limit_file);
        }
    }
    
    
}